<template>
  <div class="orders-page">
    <div class="container">
      <div class="page-header">
        <h1>我的订单</h1>
        <div class="order-tabs">
          <!-- 标签页切换时重新获取数据 -->
          <el-tabs v-model="activeTab" @tab-change="handleTabChange">
            <el-tab-pane label="全部订单" name="all" />
            <el-tab-pane label="待支付" name="pending_payment" />
            <el-tab-pane label="已确认" name="confirmed" />
            <el-tab-pane label="已完成" name="completed" />
            <el-tab-pane label="已取消" name="cancelled" />
          </el-tabs>
        </div>
      </div>

      <div class="orders-content">
        <!-- 加载状态 -->
        <div v-if="loading" class="loading-state">
          <el-skeleton :rows="5" animated />
        </div>

        <!-- 订单列表 -->
        <div v-else-if="orderList.length > 0" class="orders-list">
          <div v-for="order in orderList" :key="order.id" class="order-card">
            <div class="order-header">
              <div class="order-info">
                <span class="order-number">订单号：{{ order.bookingNo }}</span>
                <span class="order-date">{{ formatDate(order.createdAt) }}</span>
              </div>
              <div class="order-status">
                <el-tag :type="getStatusType(order.status)">
                  {{ getStatusText(order.status) }}
                </el-tag>
              </div>
            </div>

            <div class="order-content">
              <div class="property-info" @click="viewPropertyDetail(order.propertyId)">
                <div class="property-image">
                  <img :src="order.propertyImageUrl" :alt="order.propertyTitle" />
                </div>
                <div class="property-details">
                  <h3>{{ order.propertyTitle }}</h3>
                  <p class="property-location">
                    <el-icon><Location /></el-icon>
                    {{ order.propertyCity }}
                  </p>
                </div>
              </div>

              <div class="booking-details">
                <div class="detail-item">
                  <span class="label">入住日期</span>
                  <span class="value">{{ formatDate(order.checkInDate) }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">退房日期</span>
                  <span class="value">{{ formatDate(order.checkOutDate) }}</span>
                </div>
                <!-- 入住人数和天数需要后端 DTO 提供 -->
              </div>

              <div class="order-price">
                <div class="price-item total">
                  <span>实付款</span>
                  <span>¥{{ order.totalAmount }}</span>
                </div>
              </div>
            </div>

            <div class="order-actions">
              <div class="action-buttons">
                <!-- 按钮的显示逻辑需要根据后端的 status (数字) 来判断 -->
                <el-button v-if="order.paymentStatus === 0" type="primary" @click="payOrder(order.id)">
                  立即支付
                </el-button>
                <el-button v-if="order.status === 1" @click="cancelOrder(order.id)">
                  取消订单
                </el-button>
                <el-button v-if="order.status === 3" @click="reviewOrder(order.id)">
                  评价
                </el-button>
                <el-button @click="viewOrderDetail(order.id)">
                  查看详情
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-else class="empty-state">
          <el-empty :description="activeTab === 'all' ? '您还没有任何订单' : `暂无“${getStatusText(activeTab)}”状态的订单`">
            <el-button type="primary" @click="$router.push('/search')">
              去预订
            </el-button>
          </el-empty>
        </div>

        <!-- 分页功能暂时移除，因为后端目前是一次性返回所有订单 -->
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox, ElSkeleton, ElEmpty } from 'element-plus';
import request from '../../api/request'; // 引入封装的axios实例
import { Location } from '@element-plus/icons-vue';

const router = useRouter();

// 响应式状态
const activeTab = ref('all');
const orderList = ref([]); // 存储从后端获取的订单列表
const loading = ref(true);

// 状态映射表 (后端数字 -> 前端标识)
const statusMap = {
  0: { text: '待支付', type: 'warning', key: 'pending_payment' }, // 假设 0 是待支付
  1: { text: '已确认', type: 'success', key: 'confirmed' },
  2: { text: '已入住', type: 'primary', key: 'checked_in' }, // 假设 2 是已入住
  3: { text: '已完成', type: 'info', key: 'completed' },
  4: { text: '已取消', type: 'danger', key: 'cancelled' }, // 假设 4 是已取消
};


// 获取订单列表的API函数
const fetchOrders = async () => {
  loading.value = true;
  try {
    // 调用我们之前创建的后端接口
    const response = await request.get('/api/bookings/my-orders');

    // 后端返回的是 DTO 数组，可以直接使用
    orderList.value = response;

    // 如果需要前端筛选，可以在这里做。但更推荐后端直接提供筛选接口
    // if (activeTab.value !== 'all') {
    //   orderList.value = response.filter(o => statusMap[o.status].key === activeTab.value);
    // } else {
    //   orderList.value = response;
    // }

  } catch (error) {
    console.error('获取订单列表失败:', error);
    ElMessage.error('获取订单列表失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 组件挂载时自动加载数据
onMounted(() => {
  fetchOrders();
});

// 标签页切换处理
const handleTabChange = (tabName) => {
  activeTab.value = tabName;
  // 理想情况下，这里应该向后端重新发请求，并带上状态参数
  // 例如：fetchOrders({ status: tabName })
  // 目前我们先做前端筛选的简化版，在onMounted中一次性获取所有
  // (上面的fetchOrders函数中已注释掉前端筛选逻辑，因为后端目前返回所有)
  // 为了简化，我们暂时切换tab时重新调用一次，未来可以优化
  fetchOrders();
};


// 辅助函数
const getStatusType = (status) => statusMap[status]?.type || 'info';
const getStatusText = (status) => statusMap[status]?.text || '未知状态';

const formatDate = (dateString) => {
  if (!dateString) return '';
  return new Date(dateString).toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' });
};

// 用户操作方法 (桩函数，需要后端接口支持)
const payOrder = (orderId) => {
  ElMessage.info(`正在跳转到支付页面... (订单ID: ${orderId})`);
  // router.push(`/payment?orderId=${orderId}`);
};

const cancelOrder = (orderId) => {
  ElMessageBox.confirm('您确定要取消此订单吗？', '取消确认', { type: 'warning' })
      .then(async () => {
        try {
          // await request.post(`/api/bookings/${orderId}/cancel`);
          ElMessage.success('订单取消成功');
          fetchOrders(); // 重新加载列表
        } catch (error) {
          ElMessage.error('取消订单失败');
        }
      })
      .catch(() => ElMessage.info('已取消操作'));
};

const reviewOrder = (orderId) => {
  router.push({ path: '/reviews', query: { tab: 'pending', orderId: orderId } });
};

const viewOrderDetail = (orderId) => {
  router.push(`/orders/${orderId}`); // 假设有订单详情页
};

const viewPropertyDetail = (propertyId) => {
  router.push(`/property/${propertyId}`);
};

</script>

<style scoped>
.orders-page {
  min-height: 100vh;
  background: #f8f9fa;
  padding: 20px 0;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-header {
  background: white;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 30px;
}

.page-header h1 {
  font-size: 2rem;
  color: #333;
  margin-bottom: 20px;
}

.orders-content {
  space-y: 20px;
}

.orders-list {
  space-y: 20px;
}

.order-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 30px;
  background: #f8f9fa;
  border-bottom: 1px solid #eee;
}

.order-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.order-number {
  font-weight: bold;
  color: #333;
}

.order-date {
  color: #666;
  font-size: 0.9rem;
}

.order-content {
  padding: 30px;
  display: grid;
  grid-template-columns: 1fr auto auto;
  gap: 30px;
  align-items: center;
}

.property-info {
  display: flex;
  gap: 20px;
}

.property-image {
  width: 120px;
  height: 90px;
  border-radius: 8px;
  overflow: hidden;
  flex-shrink: 0;
}

.property-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.property-details h3 {
  font-size: 1.2rem;
  color: #333;
  margin-bottom: 8px;
}

.property-location {
  color: #666;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 0.9rem;
}

.booking-details {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
  min-width: 200px;
}

.detail-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.label {
  color: #666;
  font-size: 0.9rem;
}

.value {
  color: #333;
  font-weight: 500;
}

.order-price {
  text-align: right;
  min-width: 150px;
}

.price-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  color: #666;
}

.price-item.total {
  font-weight: bold;
  color: #333;
  font-size: 1.1rem;
  padding-top: 8px;
  border-top: 1px solid #eee;
}

.order-actions {
  padding: 20px 30px;
  background: #f8f9fa;
  border-top: 1px solid #eee;
}

.action-buttons {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.empty-state {
  background: white;
  border-radius: 12px;
  padding: 60px 30px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.pagination-container {
  background: white;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  text-align: center;
}

@media (max-width: 768px) {
  .order-content {
    grid-template-columns: 1fr;
    gap: 20px;
  }

  .property-info {
    flex-direction: column;
  }

  .property-image {
    width: 100%;
    height: 200px;
  }

  .booking-details {
    grid-template-columns: 1fr;
  }

  .order-price {
    text-align: left;
  }

  .action-buttons {
    flex-direction: column;
  }

  .action-buttons .el-button {
    width: 100%;
  }
  .orders-page {
    background: #f4f6f8; /* 更柔和的背景色 */
  }

  .property-info {
    cursor: pointer; /* 提示房源信息可点击 */
    transition: opacity 0.2s;
  }
  .property-info:hover {
    opacity: 0.8;
  }

  .loading-state {
    background: white;
    padding: 30px;
    border-radius: 12px;
  }
}
</style>
